package com.moyingren.springcloud.config;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class UserDetailsServicesBean implements UserDetailsService {
    private org.springframework.security.core.userdetails.User User1;


    /**
     * 这个方法是一定要重写的，spring security会根据页面传回来的用户名去查这个用户的权限和密码
     * */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//        User user = userService.getUserByUserName(userName);
        String name = "admin1";
        if (!userName.equals(name)) {
            throw new UsernameNotFoundException("用户名不正确");
        }

        System.out.println("账户密码--------------------------：" + userName);
//        Set<String> authritiesSet = new HashSet<>(user.getPermissions().size() + user.getRoles().size());
//
//        authritiesSet.addAll(user.getPermissions());
//        // 这里需要注意，security里面角色和权限都是存在一个字段里面的，但是其角色会自动加上ROLE_前缀来将角色和权限进行区分，
//        // 以便在进行判断是否有某角色时可以进行判断，但是我们一般使用是可以不用加前缀的，如@PreAuthorize("hasRole('role2')")，但是你加也没问题
//        authritiesSet.addAll(user.getRoles().stream().map(role -> "ROLE_" + role).collect(Collectors.toList()));

        UserDetails userDetails = User1.withUsername(name)
                .password("$2a$10$/KURQB4MnfFBIZKkvojBv.CFId9kwNBdzvXR51ebAF46hnQ5PfHGG")//1234
//                .authorities(authritiesSet.toArray(new String[authritiesSet.size()]))
                .authorities("add")
                .build();
        System.out.println("用户认证信息：" + userDetails);
        return userDetails;
    }
}
